<!-- eslint-disable no-trailing-spaces -->
<template>
  <el-dialog
    v-if="open"
    class="dia-style"
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="open"
    width="850px"
  >
    <hk-table
      v-if="showFirst"
      ref="tableRef"
      :loading="loading"
      :table-data="targetNameList"
      :table-columns="tableList"
      :selection="true"
      :show-index="true"
      :total="total"
      :table-height="80"
      :query-params="queryParams"
      @handleSelectionChange="handleSelectionChange"
      @changePage="getDatalist"
    />
    <hk-form
      v-else
      ref="formRef"
      :data="form"
      :rules="rules"
      :label-width="labelWidth"
      :btn-hidden="btnHidden"
      label-position="left"
      :dict-list="dictList"
      :form-labels="formLabels"
     
      @handleEvent="handleEvent"
    >
   
      <template #filter-isAll>
        <div class="inline">
          <el-select v-model="form.isAll" @change="changeIsAll">
            <el-option
              v-for="(item, index) in dictList.isAllList"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <template v-if="form.isAll==='0'">
            <el-form-item prop="nodeType">
              <el-select v-model="form.nodeType" placeholder="请选择" @change="$forceUpdate();">
                <el-option v-for="item in nodeTypeArr" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>

            <template v-if="form.nodeType&&form.nodeType !== 'day'">
              <el-form-item v-if="form.nodeType == 'week'" prop="nodeValue">
                <el-select v-model="form.nodeValue" placeholder="请选择" @change="$forceUpdate()">
                  <el-option v-for="item in 7" :label="item " :value="item" />
                </el-select>   
              </el-form-item>    
              <el-form-item v-if="form.nodeType == 'month'" prop="day">
                <el-select v-model="form.day" placeholder="请选择" @change="$forceUpdate()">
                  <el-option v-for="item in 31" :label="item " :value="item" />
                </el-select>
              </el-form-item>
            </template>
            <el-form-item prop="startTime">
              <el-time-select
                v-model="form.startTime"
                placeholder="起始时间"
                :picker-options="{
                  start: '01:00',
                  step: '01:00',
                  end: '24:00'
                }"
                @change="(val)=>changeTime(val,'startTime')"
              />
            </el-form-item>
            <el-form-item prop="endTime">
              <el-time-select
                v-model="form.endTime"
                placeholder="结束时间"
                :picker-options="{
                  start: '01:00',
                  step: '01:00',
                  end: '24:00',
                  minTime: form.startTime
                }"
                @change="(val)=>changeTime(val,'endTime')"
              />
            </el-form-item>
          </template>
        </div>
      </template>
    </hk-form>

    <div slot="footer" class="dialog-footer">
      <el-button v-if="showFirst" type="primary" :disabled="!selection.length" @click="showFirst=false">下一步</el-button>
      <el-button v-else type="primary" @click="submitForm">保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import HkTable from '@/components/Hk-Table/index.vue'
import HkForm from '@/components/Hk-Form'
import { queryById, saveOrUpdate, getTargetList } from '@/api/approval/maintenancePermissions.js'

export default {
  components: { HkForm, HkTable },
  props: {
    title: {
      type: String,
      default() {
        return '标题'
      }
    },
    targetType: {
      type: String,
      default() {
        return ''
      }
    },
    dictList: {
      type: Object,
      default: () => {}
    },
    terminalObj: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      showFirst: true,
      // 是否显示弹出层
      open: false,
      // 标题宽度
      labelWidth: '100',
      // 是否显示按钮
      btnHidden: true,
      // 总条数
      total: 0,
      // 遮罩层
      loading: false,
      // 选中数组
      selection: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 表格数据
      terminalNameList: [],
      targetNameList: [],
      //  表格
      tableList: [
        { label: '名称', param: 'deviceName' },
        { label: 'IP', param: 'ip' }

      ],

      // 查询参数
      queryParams: {
        size: 50,
        current: 1
      },
      // 表单项配置
      formLabels: [
        {
          label: '运维方式',
          field: 'type',
          type: 'select',
          span: 24,
          list: 'typeList'
        },
        {
          label: '允许协议',
          field: 'protocol',
          type: 'textarea',
          attrs: {
            placeholder: '多个协议通过“，”分割输入'
          },
          span: 24,
          hidden: true
        },
        {
          label: '允许端口',
          field: 'port',
          type: 'textarea',
          attrs: {
            placeholder: '多个端口通过“，”分割输入'
          },
          span: 24,
          hidden: true
        },
        {
          label: '允许时段',
          field: 'isAll',
          type: 'slot',
          span: 24
        }
      ],
      form: {
        startTime: '',
        endTime: ''
      },
      // 表单校验
      rules: {
        terminalName: [{ required: true, message: '不能为空', trigger: 'blur' }],
        targetName: [{ required: true, message: '不能为空', trigger: 'blur' }],
        protocol: [{ required: true, message: '不能为空', trigger: 'blur' }],
        port: [{ required: true, message: '不能为空', trigger: 'blur' }],
        isAll: [{ required: true, message: '不能为空', trigger: 'change' }],
        nodeType: [{ required: true, message: '不能为空', trigger: 'change' }],
        type: [{ required: true, message: '不能为空', trigger: 'change' }],
        day: [{ required: true, message: '不能为空', trigger: 'change' }],
        nodeValue: [{ required: true, message: '不能为空', trigger: 'change' }],
        startTime: [{ required: true, message: '不能为空', trigger: 'change' }],
        endTime: [{ required: true, message: '不能为空', trigger: 'change' }]
      },

      nodeTypeArr: [
        {
          label: '每天',
          value: 'day'
        },
        {
          label: '每周',
          value: 'week'
        },
        {
          label: ' 每月',
          value: 'month'
        }
      ]
    }
  },

  mounted() {},
  methods: {

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection.map(item => {
        const { ip: targetIp, deviceName: targetName, userName: targetUserName, assetsType: targetType } = item
        return {
          targetIp, targetName, targetUserName, targetType
        }
      })
      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    /** 查询用户列表 */
    getDatalist(val) {
      this.loading = true
      this.queryParams = { ...this.queryParams, ...val, scrollToTop: true, type: this.targetType }

      getTargetList(this.queryParams).then(res => {
        this.total = res.total
        this.targetNameList = res.list
        this.loading = false
        this.queryParams.scrollToTop = false
      })
    },
    // 打开页面
    show(id) {
      this.queryParams = {
        size: 50,
        current: 1
      }
      // this.$refs.formRef?.resetForm('formLabels')
      this.getDatalist()
      this.formLabels.forEach(item => {
        if ('hidden' in item) {
          item.hidden = true
        }
      })
      if (!id) {
        this.reset()
        this.open = true
      } else {
        queryById(id).then(res => {
          this.form = res
          if (res.timeInterval.length) {
            this.$set(this.form, 'startTime', res.timeInterval[0])
            this.$set(this.form, 'endTime', res.timeInterval[1])
          }
          this.open = true
        })
      }
    },
    // 表单变更
    handleEvent(obj) {
      if (obj.field === 'type') {
        if (obj.value == 1) {
          this.formLabels.forEach(item => {
            if ('hidden' in item) {
              item.hidden = false
            }
          })
        } else {
          this.$set(this.form, 'protocol', '')
          this.$set(this.form, 'port', '')

          this.formLabels.forEach(item => {
            if ('hidden' in item) {
              item.hidden = true
            }
          })
        }
      }
    },
    // 改变允许时间段
    changeIsAll(val) {
      if (val * 1) {
        this.$set(this.form, 'nodeType', '')
        this.$set(this.form, 'nodeValue', '')
        this.$set(this.form, 'startTime', '')
        this.$set(this.form, 'endTime', '')
      }
    },
    // 时间选择器回显
    changeTime(val, item) {
      this.$forceUpdate()
      this.$set(this.form, item, val)
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs.formRef.handleFormSubmit('formLabels').then(res => {
        if (this.form.isAll === '0') {
          const { nodeType, nodeValue, startTime, endTime } = this.form
          const arr = [nodeType, nodeValue, startTime, endTime].filter(item => item)
          this.form.cron = arr.join('_')
        } else {
          this.form.cron = ''
        }
        if (this.form?.id) {
          saveOrUpdate(this.form).then(response => {
            this.$modal.msgSuccess('修改成功')
            this.open = false
            this.$emit('handleSubmit')
          })
        } else {
          const newForm = this.selection.map(item => {
            return { ...item, ...this.terminalObj, ...this.form }
          })

          saveOrUpdate(newForm).then(response => {
            this.$modal.msgSuccess('新增成功')
            this.open = false
            this.$emit('handleSubmit')
          })
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.showFirst = true
      this.form = { startTime: '',
        endTime: '' }
      this.queryParams = {
        size: 50,
        current: 1
      }
      this.selection = []
      this.$refs.formRef?.resetForm('formLabels')
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-dialog__body {
  height: 630px;
}
.inline {
  display: flex;
  align-items: center;
  width: 100%;
  & > div {
    width: 146px;
    & + div {
      margin-left: 10px;
    }
  }
}
.targetTable{
  height: 100%;
}
::v-deep{
  .el-date-editor.el-input, .el-date-editor.el-input__inner{
    width: auto;
  }
}
</style>
